package com.woniu40.petai_user.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.druid.sql.dialect.oracle.ast.OracleDataTypeIntervalYear;
import com.github.pagehelper.PageInfo;
import com.woniu40.petai_user.entity.*;

import com.woniu40.petai_user.entity.Comment;
import com.woniu40.petai_user.entity.Dynamic;
import com.woniu40.petai_user.entity.Report;
import com.woniu40.petai_user.result.ResponseResult;
import com.woniu40.petai_user.service.CommentService;
import com.woniu40.petai_user.service.DynamicService;
import com.woniu40.petai_user.service.PlateService;
import com.woniu40.petai_user.service.ReportService;
import com.woniu40.petai_user.vo.*;
import com.woniu40.petai_user.vo.CommentVo;
import com.woniu40.petai_user.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Date;

import java.util.Map;
import java.util.UUID;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("dynamic")
@CrossOrigin
public class DynamicController {

    @Autowired
    DynamicService dynamicService;

    @Autowired
    ReportService reportService;

    @Autowired
    CommentService commentService;

    @Autowired
    UserService userService;

    @Autowired
    PlateService plateService;

    @Value("${filepath}")
    String filepath;

    @RequestMapping("/findDynamicUser")
    public String privateHome(Integer userId, Map map){
        UserVo userVo = userService.findUserByUsericon(userId);
        map.put("userInfo",userVo);
        return "private-home" ;
    }

    @RequestMapping("/dynamicList")
    @ResponseBody
    public ResponseResult<PageInfo<DynamicVo>> dynamicList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                           @RequestParam(value = "plateId", defaultValue = "0") Integer plateId, String like,
                                                           @RequestParam(value = "order", defaultValue = "1") Integer order) {
        ResponseResult<PageInfo<DynamicVo>> result = new ResponseResult<>();
        PageInfo<DynamicVo> dynamicVoPageInfo = dynamicService.findDynamicByPage(pageNum, pageSize, plateId, like, order);
        for (DynamicVo d : dynamicVoPageInfo.getList()) {
            List<CommentVo> commentVoList = commentService.listCommentVo(d.getDynamicId());
            d.setCommentNumber(commentVoList.size());
            if(d.getContentText().length()>200){
                d.setShortContent(d.getContentText().substring(0,200)+"......");
            }else{
                d.setShortContent(d.getContentText());
            }
        }
        result.setMessage("查询成功！");
        result.setData(dynamicVoPageInfo);
        return result;
    }

    @RequestMapping("/dynamicByUid")
    public String selectDynamicByUid(Integer uid,Map map){
        List<Dynamic> dynamics = dynamicService.selectAll(uid);
        map.put("dynamicList",dynamics);
        return "xxxx";
    }

    @RequestMapping("/attentionUsers")
    @ResponseBody
    public ResponseResult<List<User>> findAttentionUsers(HttpSession session, Map map) {
        //拿到登陆的用户信息
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();

        //查到关注量最多的五个用户: 不能有用户已关注的，不能有用户本身
        List<User> users = dynamicService.findAttentionUsers(userId);
        ResponseResult<List<User>> result = new ResponseResult<>();
        if (users != null) {
            result.setCode(200);
            result.setMessage("查询成功!!!");
            result.setData(users);
        } else {
            result.setCode(107);
            result.setMessage("查询失败...");
        }
        map.put("AttentionUsers", result);
        return result;
    }

    //点击热门博主，显示博主个人信息和发表的动态
    @RequestMapping("/userAndDynamic")
    public String findUserAndDynamic(Integer userId, Map map) {

        User user = dynamicService.findUser(userId);
        List<Dynamic> dynamics = dynamicService.findDynamicsByUserId(userId);
        map.put("user", user);
        map.put("dynamics", dynamics);
        return "userDynamic";
    }

    //点击关注、取关
    @RequestMapping("/changeAttention")
    public String changeAttention(HttpSession session, Integer attentionUserId,Integer isAttention) {
        //拿到登陆的用户信息
        User user = (User) session.getAttribute("user");

        int userId = user.getUserId();
        if(isAttention == 1){//表示已关注
            dynamicService.removeAttention(userId,attentionUserId);
        }else if(isAttention == 0){//表示还未关注
            Attention attention = new Attention(userId, attentionUserId);
            dynamicService.addAttention(attention);
        }
        return "dynamic";
    }
    @RequestMapping("/queryDynamic")
    public String queryDynamic(HttpSession session,Integer DynamicId,Map map){

        Dynamic dynamic = dynamicService.findDynamic(DynamicId);
        map.put("dynamic01",dynamic);

        List<CommentVo> commentVos = commentService.listCommentVo(DynamicId);

        User user = (User) session.getAttribute("user");

        Integer isReport = 3;

        if (user==null) {
            map.put("isReport", isReport);
        } else {
            int userId = user.getUserId();
            List<Report> dreport = reportService.findDreport(userId, DynamicId);
            for (Report r:dreport){
                if (r == null) {
                    map.put("isReport", isReport);
                } else {
                    isReport = r.getState();
                    map.put("isReport", isReport);
                    break;
                }
            }
        }

        for (CommentVo commentVo : commentVos) {
            String commentContent = commentVo.getCommentContent();
            String userName = commentVo.getUserName();
            Date createTime = commentVo.getCreateTime();
        }

        map.put("commentVos",commentVos);
        map.put("dynamicId",DynamicId);

        return "blog-details";
    }

    @RequestMapping("/addDynamic")
    public String add(String dynamicTitle,Integer plateId,@RequestParam("fileImg") MultipartFile fileImg,String contentText,HttpSession session){
        String originalFilename = fileImg.getOriginalFilename();
        String fileEnd = originalFilename.substring(originalFilename.indexOf("."));
        String fileName = "d_" + UUID.randomUUID().toString() + fileEnd;
        try {
            fileImg.transferTo(new File(filepath + File.separator + "dynamic" + File.separator + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        User user = (User) session.getAttribute("user");
        Dynamic dynamic = new Dynamic();
        dynamic.setDynamicCover(fileName);
        dynamic.setUserId(user.getUserId());
        dynamic.setDynamicTitle(dynamicTitle);
        dynamic.setPlateId(plateId);
        dynamic.setContentText(contentText);
        dynamic.setCreateTime(new Date());
        int i = dynamicService.addDynamic(dynamic);
        ResponseResult<String> result = new ResponseResult<>();
        result.setCode(200);
        result.setMessage("添加成功！");
        return  "redirect:/dynamic";
    }

    @RequestMapping("/report")
    public String report(Integer dynamicId,Map map){
        System.out.println(dynamicId);
        map.put("dynamicId",dynamicId);
        return  "report";
    }



}
